//
//  ST_RecommendStyleRegisterViewController.swift
//  btvideo
//
//  Created by mac on 2020/9/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwifterSwift
import RxCocoa
import RxSwift

class ST_RecommendStyleRegisterViewController: UIViewController ,ST_RegisterRouteProtocol{
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.white
        view.addSubview(title_nav_btn)
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.height.equalTo(44)
        }
        
        
        
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(title_nav_btn.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        
        view.addSubview(love_btn)
        
        love_btn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-25)
            make.centerX.equalToSuperview()
            make.width.equalTo(260)
            make.height.equalTo(44)
        }
        
        binding()
        
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
        
    }
    
    
    
    fileprivate func binding(){
        
        
        
        Observable.zip(TIANSession(requestUrl: PH.getReFeatureListApi).wrap_response_data().retry(), SCComponets.location_component.city_observer.compactMap({ $0 })).subscribe { json,city in
            
                let aArray = json["data"].arrayValue.map { (itemJson) -> SameCityRegisterModel in
                    let m = SameCityRegisterModel.init(fromJson: itemJson)
                    m.address = city
                    return m
                }
                
                self.recommend_array = aArray
                
                self.previewArray = aArray.map { (item) -> ST_MWPhoto in
                    
                    guard let url = item.content.big_remote_image().url , let media = ST_MWPhoto.init(url: url) else{
                        return ST_MWPhoto()
                    }
                    
                    return media
                }
                
                
                self.collectionView.reloadData()
                self.collectionView.mj_header?.endRefreshing()
                self.collectionView.mj_footer?.endRefreshing()
            
            
        }.disposed(by: rx.disposeBag)
        
   }
    
    //     MARK: - Properties
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
        
        var str = "为你推荐符合你要求的同城小姐姐"
        
        if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex,sex == .female{
            str = "为你推荐符合你要求的同城小哥哥"
        }
        
        control.setTitleForAllStates(str)
        
        return control
    }()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = 7
        controlLayout.minimumInteritemSpacing = 5
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: SameCityRegisterCell.self)
        control.contentInset = UIEdgeInsets.init(top: 20, left: 15, bottom: BTSafeAreaBottom + 40 + 25, right: 15)
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xFEC207)
        control.cornerRadius = 20
        control.setTitleForAllStates("一键全部喜欢")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    /**
     推荐特质
     */
    fileprivate lazy var recommend_array = [SameCityRegisterModel]()
    
    
    fileprivate var previewArray = [ST_MWPhoto]()
    
    
    @objc fileprivate func love_handle(){
        
        
        self.love_btn.isUserInteractionEnabled = false
                
        main_thread_execute(afterDelay: 2) {
            self.love_btn.isUserInteractionEnabled = true
        }
        
        //TianRegisterStepManager.shared.pushNextStepAction()
        
        pushNextRegisterController(parameters: nil)
        
    }
}

//MARK: - Delegate
extension ST_RecommendStyleRegisterViewController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return recommend_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return recommend_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: SameCityRegisterCell.self, for: indexPath)
        
        if let m = recommend_array[safe:indexPath.item]{
            cell.cellModel = m
        }
        
        return cell
        
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        guard let browser = ST_MWPhotoBrowser.init(photos: self.previewArray) else{
            return
        }
        
        browser.displayActionButton = false
        
        browser.setCurrentPhotoIndex(indexPath.row.uInt)
        
        let nav = UINavigationController.init(rootViewController: browser)
        
        GlobalPresent(toController: nav)
        
        
    }
    
    
}

//MARK: - Cell
class SameCityRegisterCell: UICollectionViewCell {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.backgroundColor = Color.white
        self.contentView.clipsToBounds = true
        //        self.contentView.backgroundColor = Color.random
        
        contentView.addSubview(cover_image_view)
        
        contentView.addSubview(avatar_image_view)
        contentView.addSubview(content_label)
        
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.right.left.equalToSuperview()
            make.bottom.equalToSuperview().offset(-22-6-5)
        }
        
        avatar_image_view.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(6)
            make.left.equalTo(cover_image_view).offset(5)
            make.width.height.equalTo(22)
        }
        
        content_label.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatar_image_view)
            make.left.equalTo(avatar_image_view.snp.right).offset(5)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //    fileprivate lazy var pauseSignImageView:UIImageView = {
    //        let control = UIImageView.init(image: ST_ImageUtils.imageName("pause"))
    //        control.isHidden = true
    //        return control
    //    }()
    
    
    fileprivate lazy var cover_image_view:ST_PairsCenterPeculiarityImageView = {
        let control = ST_PairsCenterPeculiarityImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 22/2.0
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    //    MARK: - Bind Model
    var cellModel:SameCityRegisterModel?{
        didSet{
            
            
            guard let model = cellModel else { return }
            
            content_label.text = model.age.string + "岁 " + model.address
            
            avatar_image_view.pin_setImage(from: model.avatar.compress_small_image(width: 22*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            cover_image_view.pin_setImage(from: model.content.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
        }
    }
}



//MARK: - Model


class SameCityRegisterModel : NSObject{
    
    var address : String
    var age : Int
    var avatar : String
    var content : String
    var featureId : Int
    var featureName : String
    var height : CGFloat
    var width : CGFloat
    
    
    lazy var displayHeight:CGFloat = {
        
        let w = self.width < 1 ? 1 : self.width
        
        let h = (ScreenWidth - 7 - 15 * 2)/2/w*height
        
        return h
    }()
    
    var size = CGSize.zero
    
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        address = json["address"].stringValue
        age = json["age"].intValue
        avatar = json["avatar"].stringValue
        content = json["content"].stringValue
        featureId = json["feature_id"].intValue
        featureName = json["feature_name"].stringValue
        height = json["height"].floatValue.cgFloat
        width = json["width"].floatValue.cgFloat
        
        super.init()
        
        size = CGSize.init(width: (ScreenWidth - 7 - 15 * 2)/2, height: self.displayHeight)
        
    }
}



